import { API } from "../../utils/network/api";
import { httpRequest, showContent } from "../../utils/network/network";

import Notify from "@vant/weapp/notify/notify";
import { checkUserAuthUtils, previewImageUtils, toCamelCaseUtils } from "../../utils/index";

const app = getApp();

const notify = Notify;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    loginStatus: app.globalData.loginStatus,
    activeTab: "NOT_COMPLETE",
    completeList: [],
    notCompleteList: [],
    visibleLoveListPopup: false,
    relationRadio: app.globalData.relationRadio,
    statusRadio: app.globalData.statusRadio,
    id: "",
    title: "",
    substance: "",
    remark: "",
    visibleRange: "LOVERS",
    status: "NOT_COMPLETE",
    popupType: "add",
    fileList: [],
    pageNum: 1,
    pageSize: 10
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getLoveList("NOT_COMPLETE");
    this.getLoveList("COMPLETE");
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (!this.data.loginStatus) {
      this.setData({
        loginStatus: app.globalData.loginStatus
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      [`${toCamelCaseUtils(this.data.activeTab)}List`]: []
    });
    this.data.pageNum = 1;
    this.data.pageSize = 10;
    this.getLoveList(this.data.activeTab);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.data.pageNum++;
    this.getLoveList(this.data.activeTab);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  changeTab(e) {
    this.setData({
      activeTab: e.detail.name,
      [`${toCamelCaseUtils(e.detail.name)}List`]: [], // 清空列表
    })
    this.data.pageNum = 1;
    this.data.pageSize = 10;
    this.getLoveList(e.detail.name);
  },
  /**
   * 获取恋爱清单
   * @param {*} tabName 
   */
  async getLoveList(tabName) {
    if (!this.data.loginStatus) {
      return;
    }
    let loveList = this.data[`${toCamelCaseUtils(tabName)}List`];
    const res = await httpRequest(API.getLoveList, { status: tabName, pageNum: this.data.pageNum, pageSize: this.data.pageSize });
    loveList.push(...res.data.recordedList);
    if (tabName == "NOT_COMPLETE") {
      this.setData({
        notCompleteList: loveList
      })
    } else {
      this.setData({
        completeList: loveList
      })
    }
  },
  // 添加恋爱清单
  changeVisible() {
    this.setData({
      visibleLoveListPopup: !this.data.visibleLoveListPopup
    })
    if (!this.data.visibleLoveListPopup) {
      this.clearForm();
    }
  },
  getItemInfo(e) {
    const item = e.currentTarget.dataset.item;
    let that = this;
    wx.showActionSheet({
      itemList: ["详情", "修改", "删除"],
      async success(res) {
        switch (res.tapIndex) {
          case 0:
            Notify({
              duration: app.globalData.notifyDuration,
              type: "warning",
              message: "敬请期待该功能～",
            })
            break;
          case 1:
            // if (!checkUserAuthUtils(item.userId, app.showNoAuthMessage, "清单")) return;
            const res = await that.getLoveListsInfo(item.id);
            that.setData({
              id: res.id,
              title: res.title,
              substance: res.substance,
              cover: res.cover,
              fileList: [{
                status: "done",
                url: res.cover,
                filePath: res.cover
              }],
              status: res.status,
              visibleRange: res.visibleRange,
              remark: res.remark,
              popupType: "update"
            })
            that.changeVisible();
            break;
          // delete lovers list
          case 2:
            if (!checkUserAuthUtils(item.userId, app.showNoAuthMessage, "清单")) return;
            httpRequest(`${API.loveList}/${item.id}`, {}, "DELETE").then(res => {
              Notify({
                type: "success",
                duration: app.globalData.notifyDuration,
                message: res.message,
                onClose: () => {
                  that.data.notCompleteList = [];
                  that.getLoveList("NOT_COMPLETE");
                }
              })
            }).catch(err => {
              wx.showModal({
                title: "删除失败",
                content: err.message || "删除失败",
                showCancel: false,
              })
            })
            break;
          default:
            Notify({
              duration: app.globalData.notifyDuration,
              type: "warning",
              message: "敬请期待该功能～"
            })
        }
      },
    })
  },
  clearForm() {
    this.setData({
      id: "",
      title: "",
      substance: "",
      status: "NOT_COMPLETE",
      visibleRange: "LOVERS",
      fileList: [],
      cover: "",
      remark: ""
    })
  },
  async createAndUpdateLoveList() {
    const uploadImageComponent = this.selectComponent("#upload_lover_list_image");
    let params = {
      id: this.data.id || "",
      title: this.data.title,
      status: this.data.status || "NOT_COMPLETE",
      cover: null,
      substance: this.data.substance,
      remark: this.data.remark,
      visibleRange: this.data.visibleRange
    }
    if (!params.title || !params.substance || !params.visibleRange || !uploadImageComponent.getImageList().length) {
      Notify({
        duration: app.globalData.notifyDuration,
        type: "warning",
        message: "请输入必填项"
      })
      return;
    }
    // upload image
    const fileList = await uploadImageComponent.uploadImage();
    params.cover = fileList[0].filePath;
    const statusDict = {
      "add": "创建",
      "update": "更新"
    }
    const popupType = this.data.popupType;
    let _this = this;
    httpRequest(popupType == "add" ? API.addLoveList : API.updateLoveList, params, "POST", "application/json").then(res => {
      Notify({
        duration: app.globalData.notifyDuration,
        type: "success",
        message: res.message,
        onClose: () => {
          _this.changeVisible();
          _this.setData({
            [`${toCamelCaseUtils(_this.data.activeTab)}List`]: []
          })
          _this.getLoveList(_this.data.activeTab);
          // init
          _this.setData({
            popupType: "add"
          });
        }
      })
    })
      .catch(err => {
        wx.showModal({
          title: `${statusDict[popupType]}清单失败`,
          content: err.message || `${statusDict[popupType]}清单失败`,
          showCancel: false
        })
      })
  },
  changeShow() {
    this.setData({
      show: !this.data.show
    })
  },
  cancelLogin(e) {
    this.setData({
      show: e.detail.show
    })
  },
  successLogin() {
    this.setData({
      loginStatus: wx.getStorageSync("loginStatus"),
      show: false
    })
    this.getLoveList("NOT_COMPLETE");
    this.getLoveList("COMPLETE");
  },
  loadImageError(e) {
    showContent(e.detail);
  },
  async getLoveListsInfo(id) {
    return (await httpRequest(`${API.loveList}/${id}`)).data;
  },
  preImage(e) {
    previewImageUtils([e.currentTarget.dataset.cover]);
  }
})